package lol.oxguy3.android.mcmc;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;

/**
 * A service that runs as long as the user is logged into Minecraft.net. It manages
 * sending keep-alive packets to Minecraft.net, and while a connection to a server
 * is active, it will also call the packet reading method for NetMcmcHandler
 * 
 */
public class TickService extends Service implements Runnable {
	
	boolean isRunning = false;
	NetMcmcHandler sendQueue = null;
	
	long ticksRun = 0;
	final long SLEEP_TIME = 100;
	Object derp = new Object();
	
	SharedPreferences sprefs;
	
	public static TickService bsService; //workaround for inexplicable nullification of mService
	
    // Binder given to clients
    private final IBinder mBinder = new LocalBinder();

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
    	public TickService getService() {
            // Return this instance of TickService so clients can call public methods
            return TickService.this;
        }
    }
	
	
	@Override
	public IBinder onBind(Intent i) {
		return mBinder;
	}

	@Override
	public void onCreate() {
		//Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
		sendQueue = null;
		sprefs = getSharedPreferences("login", MODE_PRIVATE);
		
		new Thread(this).start();
	}

	
	@Override
	public void onDestroy() {
		//Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
	}
	
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startid) {
		return START_STICKY;
	}
	
	public void startManagingPackets(NetMcmcHandler sq) {
		sendQueue = sq;
		isRunning = true;
		synchronized (derp) {
			derp.notify();
		}
	}
	
	public void stopManagingPackets() {
		sendQueue = null;
		isRunning = false;
	}

	public void run() {
		synchronized (derp) {
			try {
				derp.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		while (isRunning) {
			
			if (sendQueue != null){
				sendQueue.processReadPackets();
				/*if (ticksRun%10==0)
					System.out.println("sendqueue");*/
			} /*else {
				if (ticksRun%10==0)
					System.out.println("no sendqueue");
			}*/
//			if (ticksRun == 6000) {
//				
//				HttpsURLConnection connection = null;
//				
//			    try {
//			    	if (sprefs.getString("username", "@").equals("@") || sprefs.getString("sessionid", "@").equals("@")) {
//			    		
//			    		throw new Exception("Minecraft.net session information missing");
//			    	}
//			    	
//			    	String urlParameters = "user=" + URLEncoder.encode(sprefs.getString("username",""), "UTF-8") + "&session=" + URLEncoder.encode(sprefs.getString("sessionid",""), "UTF-8");
//			    	
//			    	URL url = new URL("https://login.minecraft.net/session");
//					connection = (HttpsURLConnection) url.openConnection();
//					
//					connection.setRequestMethod("GET");
//					connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//					connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
//					connection.setRequestProperty("Content-Language", "en-US");
//	
//					connection.setUseCaches(false);
//					connection.setDoInput(true);
//					connection.setDoOutput(true);
//	
//					connection.connect();
//					
//					
//					Certificate[] certs = connection.getServerCertificates();
//					AssetManager am = /*cxt.*/getAssets();
//					byte[] bytes = new byte[294];
//					
//					DataInputStream dis = new DataInputStream(am.open("minecraft.key")/*Util.class.getResourceAsStream("minecraft.key")*/);
//					dis.readFully(bytes);
//					dis.close();
//	
//					Certificate c = certs[0];
//					PublicKey pk = c.getPublicKey();
//					byte[] data = pk.getEncoded();
//	
//					for (int i = 0; i < data.length; i++) {
//						if (data[i] == bytes[i])
//							continue;
//						throw new RuntimeException("Public key mismatch");
//					}
//	
//					DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
//					wr.writeBytes(urlParameters);
//					wr.flush();
//					wr.close();
//	
//					InputStream is = connection.getInputStream();
//					BufferedReader rd = new BufferedReader(new InputStreamReader(is));
//	
//					StringBuffer response = new StringBuffer();
//					String line;
//					while ((line = rd.readLine()) != null) {
//						response.append(line);
//						response.append('\r');
//					}
//					rd.close();
//					
//					
//			    } catch (Exception e) {
//			    	e.printStackTrace();
//			    	
//			    } finally {
//			    	if (connection != null) {
//			    		connection.disconnect();
//			    	}
//			    }
//				
//			}
			
			ticksRun++;
			
			
			
			try {
				Thread.sleep(SLEEP_TIME);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("thread dying...");
		stopSelf();
	}
}
